#!/bin/sh

MODNAME='dhcpMacOui'

function get_pid_dhcpdmacoui()
{
  ps | grep "/var/dhcp/dhcpd_mac_oui.conf" |
  grep "/usr/sbin/dhcpd" |
  while read a1 a2; do echo $a1; done
}

case "$1" in
  start|restart)
    . /opt/$MODNAME/etc/settings
    if [ "$1" = "restart" ]; then
      echo -n "Restarting module $MODNAME: "
      pid=$(get_pid_dhcpdmacoui)
      if [ ! -z "$pid" ]; then
        kill $pid
      fi
    else
      echo -n "Starting module $MODNAME: "
    fi
    if [ "$MOD_DHCPMACOUI_ENABLED" != "1" ]; then
      echo "skipped"
      exit 0
    fi
    ifconfig_out=$(ifconfig "$MOD_DHCPMACOUI_INTERFACE" | grep "addr:")
    if [ "$?" -ne "0" ]; then
      echo "Interface:$MOD_DHCPMACOUI_INTERFACE not available"
      exit 1
    fi
    server_addr=$(echo $ifconfig_out | while read a1 a2 a3; do echo $a2; done)
    server_addr=${server_addr#*addr:}
    netmask=$(echo $ifconfig_out | while read a1 a2 a3 a4 a5; do echo $a4; done)
    netmask=${netmask#*Mask:}
    cfgstr='max-lease-time 86400;\nmin-lease-time 60;\n\n'
    pools=''
    last_pool='pool {\n'
    i=0
    while true
    do
      if [ "$i" -ge "8" ]; then
        break
      fi
      mac_pref=$(grep "MAC_OUI$i" /opt/$MODNAME/etc/settings)
      ip=$(grep "IP_ADDR$i" /opt/$MODNAME/etc/settings)
      ip=${ip##*=}
      ip="${ip/-/ }"
      ip="${ip//\"/}"
      mac_pref=${mac_pref##*=}
      mac=${mac_pref%:}
      if [ -n "$mac" ] && [ -n "$ip" ]; then
        octets=$(echo "${mac//[^:]}" | wc -c)
        cfgstr="$cfgstr""class \"host$((i + 1))\" {\n"
        cfgstr="$cfgstr""  match if substring(hardware, 1, $octets) = $mac;\n}\n"
        pools="$pools""  pool {\n"
        pools="$pools""    allow members of \"host$((i + 1))\";\n"
        pools="$pools""    range $ip;\n  }\n"
        last_pool="$last_pool""    deny members of \"host$((i + 1))\";\n"
      fi
      i=$((i + 1))
    done
    last_pool="$last_pool    range $MOD_DHCPMACOUI_POOL_START $MOD_DHCPMACOUI_POOL_END;\n  }"
    if [ -z "$MOD_DHCPMACOUI_POOL_START" ] && [ -z "$MOD_DHCPMACOUI_POOL_END" ]; then
      last_pool=""
    fi
    network=$(ipcalc -n "$server_addr" "$netmask")
    network=${network##*=}
    echo -e "\n$cfgstr\nsubnet $network netmask $netmask {\n\
  option routers $server_addr;\n\
  option domain-name-servers $server_addr;\n\
  default-lease-time 600;\n$pools\
  $last_pool\n}" > /var/dhcp/dhcpd_mac_oui.conf
    touch /var/dhcp/dhcpd_mac_oui.leases
    /usr/sbin/dhcpd -q -cf /var/dhcp/dhcpd_mac_oui.conf -lf /var/dhcp/dhcpd_mac_oui.leases "$MOD_DHCPMACOUI_INTERFACE" &
  ;;
  stop)
    pid=$(get_pid_dhcpdmacoui)
    if [ ! -z "$pid" ]; then
      kill $pid
    fi
  ;;
  defaults)
    cp /opt/$MODNAME/etc/defaults /opt/$MODNAME/etc/settings 2> /dev/null
  ;;
  *)
    echo "Usage: $0 {start|stop|restart|status|defaults}"
    exit 1
esac
